const fs=require('fs');
const request=require('request');
const {spawn}=require('child_process');
const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function init(){
    if (fs.existsSync('./chong.ts'))
    {
        fs.unlinkSync('./chong.ts');
    }

    if (fs.existsSync('./filelist.txt'))
    {
        fs.unlinkSync('./filelist.txt');
    }

    let mutxt=fs.readFileSync('./m3u8.txt','utf-8');
    let txtArr=mutxt.split('\r\n');
    
    let klist=[];
    for (let item of txtArr){
        if (item.substring(0,4)!=='#EXT'){
            klist.push(item);
        }
    }
    console.log(`共${klist.length}块`);
    
    let index=0;

    infile();

    function infile(){
        if (index<klist.length){
            request({
                url:'https://video.acfun.cn/ea813efde7b048dbaf2fb39e35fb30e5/video/'+klist[index],
                headers:{
                    'Origin': 'http://www.acfun.cn',
                    'Referer': 'http://www.acfun.cn/v/ac10216531',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
                },
                encoding:null
            },(err,res,body)=>{
                if (err){
                    console.log(err)
                }
                console.log(body.length)

                fs.writeFileSync(`./chong.ts`,body,{
                    flag:'a'
                })
                index++;
                console.log(`合并${index}块`);
                infile()
            })
            
            
        }
    }
    
}

const margeTs=()=>{
    return new Promise((resolve,reject)=>{
        const exe=spawn('ffmpeg.exe',['-f','concat','-i','filelist.txt','-c','copy','chong.ts']);
        
        exe.on('close',(code)=>{
            resolve(code)
        })
    })
}

init();
